﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Query.Internal;
using TrackSystem.Contracts;
using TrackSystem.Entities.Dtos.Channel;
using TrackSystem.Entities.Dtos.Equip;
using TrackSystem.Entities.Dtos.Var;
using TrackSystem.Entities.Models;

namespace TrackSystem.API.Controllers
{
    /// <summary>
    /// 设备控制器接口
    /// </summary>
    [Route("api/equip")]
    [ApiController]
    public class EquipController : ControllerBase
    {
        private readonly IRepositoryWrapper wrapper;
        private readonly ILogger<ChannelController> logger;
        private readonly IMapper Mapper;

        /// <summary>
        /// 通道控制器构造函数
        /// </summary>
        /// <param name="wrapper"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public EquipController(IRepositoryWrapper wrapper,
            ILogger<ChannelController> logger,
            IMapper mapper)
        {
            this.wrapper = wrapper;
            this.logger = logger;
            Mapper = mapper;
        }

        /// <summary>
        /// 获取所有通道信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("all")]
        public async Task<IActionResult> GetAll()
        {
            try
            {
                var result = await wrapper.Equip.GetAllListAsync();
                var eqps = Mapper.Map<IEnumerable<EquipDto>>(result);

                return Ok(eqps);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[设备设置] 获取异常");
                return StatusCode(StatusCodes.Status500InternalServerError, $"[设备设置] 获取异常, {ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有通道信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("all/sensors")]
        public async Task<IActionResult> GetAllWithSensors()
        {
            try
            {
                var result = await wrapper.Equip.GetEquipWithSensorsAsync();
                var eqps = Mapper.Map<IEnumerable<EquipWithSensorsDto>>(result);

                return Ok(eqps);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[设备设置] 获取异常");
                return StatusCode(StatusCodes.Status500InternalServerError, "[设备设置] 获取异常");
            }
        }

        /// <summary>
        /// 插入新的设备信息
        /// </summary>
        /// <param name="equip"></param>
        /// <returns></returns>
        [HttpPut()]
        public async Task<ApiResult<EquipDto>> AddEquip(EquipDto equip)
        {
            try
            {
                if (equip == null)
                    return ApiResult<EquipDto>.Fail("设备数据为空", StatusCodes.Status204NoContent);

                int count = await wrapper.Equip.CountAsync(a => a.Name == equip.Name);
                if (count > 0)
                    return ApiResult<EquipDto>.Fail("存在相同名称的设备", StatusCodes.Status207MultiStatus);

                var eqp = Mapper.Map<EquipTable>(equip);
                var result = await wrapper.Equip.InsertAsync(eqp);
                return ApiResult<EquipDto>.Ok(equip, "添加设备成功");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[设备设置] 设备添加异常");
                return ApiResult<EquipDto>.Fail(ex.Message, StatusCodes.Status500InternalServerError);
            }
        }

        /// <summary>
        /// 修改设备信息
        /// </summary>
        /// <param name="equip"></param>
        /// <returns></returns>
        [HttpPost()]
        public async Task<ApiResult<EquipDto>> UpdateEquip(EquipDto equip)
        {
            try
            {
                if (equip == null)
                    return ApiResult<EquipDto>.Fail("设备数据为空", StatusCodes.Status204NoContent);

                var entity = wrapper.Equip.FirstOrDefault(a => a.Id == equip.Id);
                if (entity == null)
                    return ApiResult<EquipDto>.Fail($"找不到Id为{equip.Id}的设备", StatusCodes.Status204NoContent);

                int count = await wrapper.Equip.CountAsync(a => a.Name == equip.Name && a.Id != equip.Id);
                if (count > 0)
                    return ApiResult<EquipDto>.Fail("存在相同名称的设备", StatusCodes.Status207MultiStatus);

                entity.Name = equip.Name;
                entity.Description = equip.Description ??= "";
                var result = await wrapper.Equip.UpdateAsync(entity);
                return ApiResult<EquipDto>.Ok(equip, "更新设备成功");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[设备设置] 设备更新异常");
                return ApiResult<EquipDto>.Fail(ex.Message, StatusCodes.Status500InternalServerError);
            }
        }

        /// <summary>
        /// 删除设备信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id:int}")]
        public async Task<ApiResult<EquipDto>> DeleteEquip(int id)
        {
            try
            {
                var equip = await wrapper.Equip.SingleAsync(a => a.Id == id);
                if (equip == null)
                {
                    string errorMessage = $"设备ID为{id}的通道信息不存在";
                    return ApiResult<EquipDto>.Fail(errorMessage, StatusCodes.Status204NoContent);
                }

                var sensors = wrapper.Sensor.Count(a => a.equipId == id);
                if (sensors > 0)
                {
                    string errorMessage = $"设备ID为{id}的设备已被传感器使用，无法删除";
                    return ApiResult<EquipDto>.Fail(errorMessage, StatusCodes.Status204NoContent);
                }

                await wrapper.Equip.DeleteAsync(equip);
                return ApiResult<EquipDto>.Ok(Mapper.Map<EquipDto>(equip), "删除设备成功");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[设备删除异常]");
                return ApiResult<EquipDto>.Fail(ex.Message, StatusCodes.Status500InternalServerError);
            }
        }
    }
}
